package com.jm3.riscar3.commands;

import com.jm3.riscar3.core.Microcontroller;
import com.jm3.riscar3.exceptions.IOPortAddressingException;
import com.jm3.riscar3.helpers.BinaryTranslator;
import com.jm3.riscar3.interfaces.IAR3Command;
import com.jm3.riscar3.memory.Memory;
import com.jm3.riscar3.memory.Register;
import com.jm3.riscar3.memory.StatusRegister;
public class LDAaddr implements IAR3Command {
	
	private final String OpCode = "01100";
	private Register Accumulator;
	private Memory memory;
	private StatusRegister SR;
	
	public LDAaddr(Microcontroller mcu)
	{
		this.Accumulator = mcu.getCPU().getAcc();
		this.memory = mcu.getMemory();
		this.SR = mcu.getCPU().getSR();
	}

	@Override
	public void execute(String args) throws Exception,IOPortAddressingException {
		// TODO Auto-generated method stub
		int memLoc = BinaryTranslator.getBitValue(args.substring(3));
		if(memLoc==250||memLoc==251){
			throw new IOPortAddressingException(String.valueOf(memLoc));
		}
		else
		Accumulator.writeRegister(memory.readLocation(memLoc));
		
			//component.addkeylistener
			
		setFlags();
	}

	@Override
	public String getOpCode() {
		// TODO Auto-generated method stub
		return OpCode;
	}
	
	public void setFlags() throws Exception
	{
		int accValue = Accumulator.readRegister();
		boolean isZero = (accValue == 0);
		boolean isNegative = ((accValue & 128) != 0);
		
		SR.setZeroFlag(isZero);
		SR.setNegativeFlag(isNegative);
	}

}
